package com.lu.statistics.controller.file;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lu.statistics.common.config.ServerResponse;
import com.lu.statistics.entity.SysFile;
import com.lu.statistics.entity.front.request.CreateFile;
import com.lu.statistics.entity.front.response.FileResponse;
import com.lu.statistics.fileService.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;


@Api(value = "文件操作", tags = {"文件操作"})
@RestController
@RequestMapping("/api/file")
public class CommonFileController {
    @Autowired
    private FileUploadService fileUploadService;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @SaCheckLogin
    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public ServerResponse<FileResponse> uploadPicture(@RequestParam(value = "file") @RequestPart MultipartFile file, CreateFile createFile) {
        try {
            SysFile sysFile = new SysFile();
            sysFile.setFileNumber(createFile.getFileNumber());
            //返回原来的文件名在客户机的文件系统。
            sysFile.setFileName(file.getOriginalFilename());
            //返回文件的大小,以字节为单位。
            sysFile.setFileSize(file.getSize() / 1024.00f);
            Integer userId = Integer.parseInt(StpUtil.getLoginId().toString());
            sysFile.setCreateId(userId);
            sysFile.setFileType(createFile.fileType.name());
            //返回InputStream读取文件的内容
            SysFile sysFiles = fileUploadService.uploadFile(sysFile, file.getInputStream());
            if (sysFiles != null) {
                FileResponse newFile = new FileResponse();
                BeanUtils.copyProperties(sysFiles, newFile);
                return ServerResponse.success(newFile);
            }
        } catch (IOException e) {
            return ServerResponse.errorMessage("文件上传失败，文件格式不正确！");
        } catch (DuplicateKeyException e) {
            return ServerResponse.errorMessage("文件已存在！");
        } catch (IllegalArgumentException e) {
            return ServerResponse.errorMessage("文件内容有空值！");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.errorMessage("文件上传失败，文件格式不正确！");
        }
        return ServerResponse.errorMessage("文件上传失败！");
    }



    @ApiOperation(value = "文件预览(jpg、word、Excel、pdf)", notes = "文件预览(jpg、word、Excel、pdf)")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", required = true, name = "fileFullPath", value = "文件所指定的路径", dataType = "string")})
    @GetMapping(value = "/previewPhoto")
    public void previewPhoto(@RequestParam(value = "fileFullPath") String fileFullPath, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = downloadFile4NFS(fileFullPath);
        try {
            //需要制定路径
            String fileType = fileFullPath.substring(fileFullPath.lastIndexOf(".") + 1);
            String type = "image/jpeg";
            if ("pdf".equals(fileType)) {
                type = "application/pdf";
            }
            if ("pptx".equals(fileType)) {
                type = "application/ms-powerpoint";
            }
            if ("doc".equals(fileType) || "docx".equals(fileType)) {
                type = "application/msword";
            }
            if ("txt".equals(fileType)) {
                type = "text/plain";
            }
            if ("xlsx".equals(fileType)) {
                type = "application/x-excel";
            }
            response.setContentType(type);
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            int index = -1;
            byte[] tmp = new byte[1024];
            while ((index = inputStream.read(tmp)) != -1) {
                arrayOutputStream.write(tmp, 0, index);
            }
            byte[] buffer = arrayOutputStream.toByteArray();
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
//            LoggerUtils.error(getClass(), "[fileUpload previewPhoto]" + e.getMessage());
            e.printStackTrace();
        } finally {
            outputStream.close();
            if (inputStream != null)
                inputStream.close();

        }
    }


    private InputStream downloadFile4NFS(String fileFullPath) throws FileNotFoundException {
        String filePathPrefix = fileUploadService.getFileSavePath();
        FileInputStream fis = new FileInputStream(filePathPrefix + fileFullPath.replaceAll("\\\\", "/").substring(1, fileFullPath.replaceAll("\\\\", "/").length()));
        return fis;
    }

}
